package com.choker.mall.controller;

import com.alibaba.fastjson.JSON;
import com.choker.mall.TextUtils;
import com.choker.mall.entity.BaseResult;
import com.choker.mall.entity.Book;
import com.choker.mall.entity.User;
import com.choker.mall.service.UserService;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lychee on 2018/2/23 21:37.
 * <p>
 * Author:Hejingzhou
 * <p>
 * Email:tcowork@163.com
 */
@Controller
public class UserController {

    @Resource
    private UserService mUserService;


    @RequestMapping(value = "/login")
    public void login(@RequestParam("loginName") String loginName,
                      @RequestParam("password") String password,
                      ModelAndView modelAndView,
                      HttpSession session) {
        if (loginName != null && "Hejingzhou".equals(loginName) && password != null && "1230".equals(password)) {
            User user = new User();
            user.setUserName(loginName);
            user.setPassword(password);
            user.setNote("高级主管");
            session.setAttribute("user", user);
            modelAndView.setViewName("redirect:mainBook");
        } else {
            modelAndView.addObject("message", "用户民或者密码错误，请重新输入");
            modelAndView.setViewName("loginForm");
        }

    }


    @RequestMapping(value = "/mainBook")
    public String main(Model model) {
        List<Book> bookList = new ArrayList<Book>();
        bookList.add(new Book("书名一", "孙悟空", "100元"));
        bookList.add(new Book("书名二", "孙悟", "200元"));
        bookList.add(new Book("书名三", "孙", "300元"));
        model.addAttribute("book_list", bookList);
        return "mainBook";
    }

    /**
     * 可以使用形参作为参数的Key
     *
     * @param test
     */
    @RequestMapping(value = "/sayHello", method = RequestMethod.GET)
    public String sayHello(String test) {
        System.out.println("Hello\t" + test);
        return "hello";
    }


    /**
     * 使用@ModelAttribute注解是优先于@RequestMapping方法的调用
     * 作用是把请求的参数对应的赋给对一个的变量
     *
     * @return
     */
    //    @ModelAttribute(value = "/registerUser")
    @ModelAttribute
    public String registerView(Model model) {
        System.out.println("先调用这个  反馈给View");
        return "";
    }

    /**
     * 拿到这个请求头的数据 使用@RequestHeader获得请求的数据
     *
     * @param userAgent
     * @param accept
     * @RequestHeader
     */
    @RequestMapping(value = "/testRequestHeader", method = RequestMethod.GET)
    public void requestHeaderTest(@RequestHeader("User-Agent") String userAgent, @RequestHeader(value = "Accept") String[] accept, @RequestHeader("Keep-Alive") long keepAlive) {
        System.out.println("请求头中的User-Agent（浏览器类型）\t" + userAgent + "\n");
        for (String s : accept) {
            System.out.println("accept（浏览器可接受的MIME类型）:" + s);
        }
        System.out.println("keepAlive:" + keepAlive);

    }

    @RequestMapping("/testCookie")
    public void cooieData(@CookieValue(value = "JSESSIONID") String sessionID) {
        System.out.println("获得Cookie sessionID:" + sessionID);
    }

    /**
     * 这种可以指定这个请求的参数参数key
     *
     * @param registerUserName
     * @param registerPassword
     */
    @RequestMapping(value = "/registerNewUser")
    public void registerNewUser(@RequestParam(value = "registerName", defaultValue = "Choker.", required = true) String registerUserName, @RequestParam("registerPassword") String registerPassword) {
        System.out.println("新用户账户：" + registerUserName + "\n新用户密码：" + registerPassword);
    }

    /**
     * 将对象返回 json格式
     *
     * @return
     */
    @RequestMapping(value = "/toJson")
    @ResponseBody
    public Object conversionJson() {
        User user = new User();
        user.setUserName("hahaha");
        user.setPassword("1111100000");
        return user;
    }

    @ModelAttribute
    public void registerIntoModel(String userNameDb, String passwordDb, Model model) {
        User user = new User(userNameDb, passwordDb);
        model.addAttribute("newUserDbKey", user);
        //然后这里可以处理一些View层的表现
    }

    @RequestMapping(value = "/registerIntoModel")
    public void registerIntoModel(Model model) {
        User user = (User) model.asMap().get("newUserDbKey");
        System.out.println("使用Model接手@ModelAttribute处理好的参数\t" + user.toString());
    }

    @ModelAttribute
    public void registerIntoModelMap(String userNameModelMap, String passwordModelMap, ModelMap modelMap) {
        User user = new User(userNameModelMap, passwordModelMap);
        modelMap.addAttribute("userModelMapKey", user);
    }

    @RequestMapping(value = "/registerIntoModelMap")
    public void registerIntoModelMap(ModelMap modelMap) {
        User user = (User) modelMap.get("userModelMapKey");
        System.out.println("使用ModelMap接手的@ModelAttribute保存好的参数\t" + user.toString());
    }

    @ModelAttribute
    public void registerModelAndView(String modelViewName, String modelViewPassword, ModelAndView modelAndView) {
        User user = new User(modelViewName, modelViewPassword);
        modelAndView.addObject("user", user);
    }

    @RequestMapping(value = "/registerUserModelAndView")
    public void registerModelAndView(ModelAndView modelAndView) {
        User user = (User) modelAndView.getModelMap().get("user");
        System.out.println("使用ModelAndView接手的@ModelAttribute添加的参数\t" + user.toString());
    }

    @RequestMapping(value = "/checkUserIsExist", method = RequestMethod.GET)
    public String checkUserExist(@RequestParam("userName") String userName, ModelMap modelMap) {
        for (User user : mUserService.selectAllUser()) {
            if (user.getUserName().equals(userName)) {
                modelMap.put("currUserPassword", user.getPassword());
            } else {
                modelMap.put("currUserPassword", "用户不存在的");
            }

        }
        return "user";
    }

    /**
     * 移动端请求的接口中UrlPath段变化的话可以使用这个@PathVariable注解
     * 但是传过来的参数类型绝对要和方法形参对称，且不能为Null
     *
     * @param parame1
     * @param parame2
     */
    @RequestMapping(value = "/test/{parame1}/{parame2}")
    public void pathVariableTest(@PathVariable String parame1, @PathVariable Integer parame2) {
        System.out.println("参数1：" + parame1 + "\n参数2:" + parame2);
    }

    /**
     * xxxxxxxxxxxxxxxxxxxxxxxxx
     *
     * @param userName
     * @param password
     * @param model
     * @return
     */
    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    public String userLogin(@RequestParam("userName") String userName, @RequestParam("password") String password, Model model) {
        for (User user : mUserService.selectAllUser()) {
            if (user.getUserName().equals(userName) && user.getPassword().equals(password)) {
                User existUser = new User(userName, password);
                model.addAttribute("user", existUser);
            }
        }
        return "loginResult";
    }

    /**
     * 注册用户
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/registerUser", method = RequestMethod.GET)
    public String registerUser(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("再调用这个  反馈给移动端");
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        if (userName != null && userName.length() > 0 && password != null && password.length() > 0) {
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + "\t\t" + cookie.getValue() + "\n");
            }
            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            Integer resultItme = mUserService.registerUser(user);
            if (resultItme == 1) {
                BaseResult registerResult = new BaseResult(true, null, "注册成功");
                return new Gson().toJson(registerResult);
            }
            System.out.println("影响条数\t" + resultItme);
        }
        return "";
    }

    /**
     * 查询所有用户
     */
    @RequestMapping(value = "/selectAllUser", method = RequestMethod.GET)
    public String selectAllUser() {
        List<User> users = mUserService.selectAllUser();
        for (User user : users) {
            System.out.println(user.toString());
        }
        return "Ok";
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.GET)
    public void updateUser(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        int resultItme = mUserService.updateUser(new User(id, userName, password));
        System.out.println("影响条数\t" + resultItme);
    }

    /**
     * 删除用户信息
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        if (!TextUtils.isEmpty(id)) {
            Integer resultItem = mUserService.deleteUser(Integer.parseInt(id));
            System.out.println("影响条数\t" + resultItem);
        }
    }
}
